package com.kfit.config;

import java.util.Collection;
import java.util.Iterator;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.ConfigAttribute;
import org.springframework.security.authentication.AnonymousAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.web.util.matcher.AntPathRequestMatcher;
import org.springframework.stereotype.Service;

import com.kfit.permission.service.PermissionService;

@Service
public class AuthService {
	
	@Autowired
	private PermissionService permissionService;
	
	public boolean canAccess(HttpServletRequest request,Authentication authentication) {
		System.out.println("AuthService.canAccess()");
		boolean b = false;
		
		/*
		 * 1/未登录的情况下，需要做一个判断或者是拦截。 anonymousUser | userDetails.user
		 * 
		 */
		Object pricipal = authentication.getPrincipal();
		if(pricipal == null || "anonymousUser".equals(pricipal)) {
			return b;
		}
		
		/*
		 * 2/ 匿名的角色 ROLE_ANONYMOUS
		 */
		if(authentication instanceof AnonymousAuthenticationToken) {
			//匿名角色.
			//check.
			//return.
		}
		
		/*
		 * 3/ 通过的request对象url）获取到权限信息。
		 */
		Map<String,Collection<ConfigAttribute>> map = permissionService.getPermissionMap();
		
		//  /hello/helloUser  /hello/**
		//Collection<ConfigAttribute> collection =  map.get(request.getRequestURI());
		
		///AntPathRequestMatcher;
		Collection<ConfigAttribute> configAttributes = null;
		for(Iterator<String> it = map.keySet().iterator();it.hasNext();) {
			String curUrl = it.next();
			// /user/**  /user/useradd  /user/userdel
			AntPathRequestMatcher matcher =  new AntPathRequestMatcher(curUrl);
			if(matcher.matches(request)) {
				configAttributes = map.get(curUrl);
				break;
			}
		}
		
		if(configAttributes == null || configAttributes.size() ==0) {
			return b;
		}
		
		
		/*
		 *  4/ 将获取到的权限信息和当前的登录账号的权限信息进行比对。
		 */
		for(Iterator<ConfigAttribute> it = configAttributes.iterator();it.hasNext();) {
			ConfigAttribute cfa = it.next();
			String role= cfa.getAttribute();//ROLE_admin | ROLE_normal
			for(GrantedAuthority authority : authentication.getAuthorities()) {
				if(role.equals(authority.getAuthority())) {
					System.out.println("当前匹配到的角色是："+role);
					b = true;
					break;
				}
			}
		}
		return b;
	}
	
}
